package com.example.no1admin.service.impl;

import com.example.no1admin.ex.ServiceException;
import com.example.no1admin.mapper.AlbumMapper;
import com.example.no1admin.mapper.PictureMapper;
import com.example.no1admin.pojo.dto.picture.PictureEditDTO;
import com.example.no1admin.pojo.entity.Picture;
import com.example.no1admin.pojo.vo.album.AlbumDetailVO;
import com.example.no1admin.pojo.vo.picture.PictureDetailVO;
import com.example.no1admin.pojo.vo.picture.PictureListItemVO;
import com.example.no1admin.repo.IPictureRepository;
import com.example.no1admin.service.IPictureService;
import com.example.no1admin.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class PictureServiceImpl implements IPictureService {

    @Autowired
    private IPictureRepository pictureRepository;
    
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private AlbumMapper albumMapper;

    @Value("${dirPath}")
    private String dirPath;

    public PictureServiceImpl() {
        log.debug("创建业务逻辑对象：PictureServiceImpl");
    }

    @Override
    public String addNew(MultipartFile picFile,Long albumId) {
        log.debug("准备开始处理创建图片的业务，参数：{}",picFile);

         //得到文件的原始文件名
        String fileName = picFile.getOriginalFilename();
        log.debug("文件的原始文件名:{}",picFile);

        //得到文件名的后缀部分    abc.jpg     .jpg
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        //得到唯一的文件夹 UUID.randomUUID()得到唯一标识符 是一个字符串
        fileName = UUID.randomUUID()+suffix;
        log.debug("新文件名:{}",fileName);

        File dirFile = new File(dirPath);
        //如果不存在则创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到文件的完整路径    F:/files/xxxxx.jpg
        String filePath = dirPath+"/"+fileName;
        //把文件保存到filePath这个路径   异常输出
        try {
            picFile.transferTo(new File(filePath));
        } catch (IOException e) {
            String message = "添加图片失败，服务器忙，请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        Picture picture = new Picture();
        picture.setUrl(fileName);
        picture.setAlbumId(albumId);
        int rows = pictureMapper.insert(picture);
        if (rows!=1){
            String message = "添加图片失败，服务器忙，请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }

        return picture.getUrl();
    }

    @Override
    public String addBanner(MultipartFile partFile) {
        log.debug("准备开始处理创建图片的业务，参数：{}",partFile);
        //得到文件的原始文件名
        String fileName = partFile.getOriginalFilename();
        log.debug("文件的原始文件名:{}",partFile);

        //得到文件名的后缀部分    abc.jpg     .jpg
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        //得到唯一的文件夹 UUID.randomUUID()得到唯一标识符 是一个字符串
        fileName = UUID.randomUUID()+suffix;
        log.debug("新文件名:{}",fileName);

        File dirFile = new File(dirPath);
        //如果不存在则创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到文件的完整路径    F:/files/xxxxx.jpg
        String filePath = dirPath+"/"+fileName;
        //把文件保存到filePath这个路径   异常输出
        try {
            partFile.transferTo(new File(filePath));
        } catch (IOException e) {
            String message = "添加图片失败，服务器忙，请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }

        Picture picture = new Picture();
        picture.setUrl(fileName);
        //查轮播图相册id
        AlbumDetailVO banner = albumMapper.getByName("轮播图%");
        picture.setAlbumId(banner.getId());
        picture.setIsCover(0);
        int rows = pictureMapper.insert(picture);
        if (rows!=1){
            String message = "添加图片失败，服务器忙，请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        return picture.getUrl();
    }

    @Override
    public void deleteByName(String name) {
        log.debug("开始处理删除图片的业务,name={}",name);
        String filePath = dirPath+"/"+name;
        PictureDetailVO picture = pictureMapper.getByName(name);
        new File(filePath).delete();
        if(picture==null){
            String message = "删除图片失败，尝试删除的数据【"+name+"】不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int rows = pictureMapper.deleteByName(name);
        if(rows!=1){
            String message = "删除图片失败，服务器忙，请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理删除图片的业务,id={}",id);
        PictureDetailVO picture = pictureMapper.getById(id);
        String filePath = dirPath+"/"+picture.getUrl();
        new File(filePath).delete();
        if(picture==null){
            String message = "删除图片失败，尝试删除的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int rows = pictureMapper.deleteById(id);
        if(rows!=1){
            String message = "删除图片失败，服务器忙，请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }

    @Override
    public void updateById(PictureEditDTO pictureEditDTO) {
        //将图片数据写入到数据库
        log.debug("即将向表中插入需要修改的数据：{}",pictureEditDTO);
        int rows = pictureMapper.updateById(pictureEditDTO);
        if(rows!=1){
            String message = "修改图片失败，服务器忙，请稍后再试!";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }

    @Override
    public List<PictureListItemVO> list() {
        log.debug("开始处理查询图片列表的请求");
        return pictureRepository.getList();
    }

    @Override
    public List<PictureListItemVO> listByAlbum(Long AlbumId) {
        log.debug("开始处理根据相册id查询图片列表");
        return pictureMapper.listByAlbumId(AlbumId);
    }

    @Override
    public List<PictureListItemVO> listByAlbumName(String albumName) {
        log.debug("开始处理根据相册id查询图片列表");
        AlbumDetailVO album = albumMapper.getByName(albumName);
        Long albumId = album.getId();
        return pictureMapper.listByAlbumId(albumId);
    }

}
